﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Markup;
#if !SILVERLIGHT
using System.Xaml;
#endif

namespace UIT.Controls.Template
{
#if !SILVERLIGHT
    [Ambient]
    [XamlDeferLoad(typeof(TemplateContentLoader), typeof(IControl))]
#endif
    [ContentProperty("VisualTree")]
    public class TemplateContent
    {
        public IControl VisualTree { get; set; }

        private System.Xaml.XamlReader xamlReader;
        private System.Xaml.IXamlObjectWriterFactory factory;
        private IServiceProvider serviceProvider;
        XamlNodeList parsedTemplate;

        public TemplateContent()
        {
        }

        public TemplateContent(System.Xaml.XamlReader xamlReader, System.Xaml.IXamlObjectWriterFactory factory, IServiceProvider serviceProvider)
        {
            this.xamlReader = xamlReader;
            this.factory = factory;
            this.serviceProvider = serviceProvider;
        }

        public IControl CreateInstance()
        {
            XamlObjectWriter writer;
            if (factory != null)
            {
                var settings = new XamlObjectWriterSettings(factory.GetParentSettings());
                settings.RootObjectInstance = null;
                writer = factory.GetXamlObjectWriter(settings);
            }
            else
                writer = new XamlObjectWriter(RendererManager.XamlSchemaContext, RendererManager.XamlObjectWriterSettings);
            if (parsedTemplate == null)
            {
                if (xamlReader == null)
                    xamlReader = new UitXamlObjectReader(VisualTree, RendererManager.XamlSchemaContext, new XamlObjectReaderSettings());

                parsedTemplate = new XamlNodeList(xamlReader.SchemaContext);
                XamlServices.Transform(xamlReader, parsedTemplate.Writer);
            }
            XamlServices.Transform(parsedTemplate.GetReader(), writer);
            IControl result = writer.Result as IControl;
            if (result == null)
                result = ((TemplateContent)writer.Result).VisualTree;
            return result;
        }
    }
}
